package com.solocredit.finance.ui.user.impl

import android.content.Context
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.user.view.IMullaVerificationView
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:26
 * @Annotation：校验手机号 Presenter 实现
 */
class MullaVerificationPresenterImpl(context: Context?) : MvpPresenter<IMullaVerificationView>(context) {
    //选择类型  SMS  、 WHATSAPP
    private var selectType = ""
    //是否需要选择出生日期
    private var needSubmitBirthDay = "NO"

    fun getCheckNumberSelectType(): String{
        return selectType
    }

    /**
     * 是否需要验证生日
     */
    fun getMullaVerificationNeedSubmitBirthDay(): String{
        return needSubmitBirthDay
    }

    /**
     * 切换校验类型
     */
    fun setMullaVerificationType(type: String,isSend: Boolean = true){
        if (selectType == type){
            return
        }
        selectType = type
        mvpView?.showMullaVerificationType(type)
        if (isSend){
            sendMullaVerificationWhatsAppCodeAction()
        }
    }

    /**
     * 发送WhatsApp验证码
     */
    fun sendMullaVerificationWhatsAppCodeAction(){
        //发送验证，埋点增加手机号
        mvpView?.let {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_VERIFICATION_GETCODE,it.getMullaMobile())
        }
        mvpView?.showMullaLoading()
        val loginMobile = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE)
        val params = JSONObject().addCommonParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_WHATSAPP_SEND_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", mvpView?.getMullaMobile())
            put("sendType",selectType)
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_WHATSAPP_SEND_CODE_PATH)
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            //是否需要验证生日
                            if (obj.has("needSubmitBirthDay")){
                                needSubmitBirthDay = obj.optString("needSubmitBirthDay")
                            }
                            //当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
                            val directLoginFlag = obj.optString("directLoginFlag")
                            mvpView?.showMullaSendCodeSuccess(directLoginFlag)
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Verification Page Send Code", onRetryClick = {
                        mvpView?.showMullaLoading()
                        sendMullaVerificationWhatsAppCodeAction()
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 校验验证码
     */
    fun onMullaVerificationCodeAction(submitBirthDay: String = ""){
        //需要提交出生日期
        if (needSubmitBirthDay == "YES" && submitBirthDay.isEmpty()){
            mvpView?.showMullaChooseBirthdayDialog()
            return
        }
        mvpView?.showMullaLoading()
        val loginMobile = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE)
        val params = JSONObject().addCommonParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_WHATSAPP_CHECK_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", mvpView?.getMullaMobile())
            put("code",mvpView?.getMullaCode())
            put("checkType",getCheckNumberSelectType())
            put("needSubmitBirthDay",needSubmitBirthDay)//是否需要验证生日
        }
        if (needSubmitBirthDay == "YES" && submitBirthDay.isNotEmpty()){
            params.put("submitBirthDay",submitBirthDay)//出生日期
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_WHATSAPP_CHECK_CODE_PATH)
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView?.hideMullaLoading()
                        mvpView?.showMullaVerificationSuccess()
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Verification Page Check", onRetryClick = {
                        mvpView?.showMullaLoading()
                        onMullaVerificationCodeAction(submitBirthDay)
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}